const crypto = require('crypto');


// 支付签名算法
function generatePaymentXML({appid, mch_id, device_info, body, nonce_str, apiKey, out_trade_no, trade_type, total_fee, notify_url}) {
  const params = {
    appid: appid,
    mch_id: mch_id,
    device_info: device_info,
    body: body,
    nonce_str: nonce_str,
    out_trade_no: out_trade_no,
    trade_type: trade_type,
    total_fee: total_fee,
    notify_url: notify_url,
  };

  // 将参数按照key=value的格式，并按照参数名ASCII字典序排序
  const sortedParams = Object.keys(params)
    .sort()
    .map(key => `${key}=${params[key]}`)
    .join('&');

  // 拼接API密钥
  const stringSignTemp = sortedParams + `&key=${apiKey}`;

  // 使用 MD5 签名方式计算签名
  const sign = crypto
    .createHash('md5')
    .update(stringSignTemp, 'utf8')
    .digest('hex')
    .toUpperCase();

  // 生成最终的 XML 数据
  const xmlData = `<xml>
    <appid>${appid}</appid>
    <mch_id>${mch_id}</mch_id>
    <device_info>${device_info}</device_info>
    <body>${body}</body>
    <nonce_str>${nonce_str}</nonce_str>
    <out_trade_no>${out_trade_no}</out_trade_no>
    <trade_type>${trade_type}</trade_type>
    <total_fee>${total_fee}</total_fee>
    <notify_url>${notify_url}</notify_url>
    <sign>${sign}</sign>
  </xml>`;

  return xmlData;
}


// 随机字符串生成
function generateRandomString(length = 32) {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charLength = characters.length;
  let randomString = '';

  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * charLength);
    randomString += characters.charAt(randomIndex);
  }

  return randomString;
}

// 支付接口加密
function generateSignature(data, apiKey) {
  const sortedKeys = Object.keys(data).sort();
  const stringA = sortedKeys.map(key => `${key}=${data[key]}`).join('&');
  const stringSignTemp = stringA + `&key=${apiKey}`;
  
  const sign = crypto
    .createHash('md5')
    .update(stringSignTemp, 'utf8')
    .digest('hex')
    .toUpperCase();
  
  return sign;
}

// 生成Base64签名
function generateBase64Signature(data, apiKey) {
  const signature = generateSignature(data, apiKey);
  const buffer = Buffer.from(signature, 'hex');
  const base64Signature = buffer.toString('base64');
  return base64Signature;
}

// 示例使用：
// const data = {
//   appId: 'wx8888888888888888',
//   timeStamp: '1414561699',
//   nonceStr: '5K8264ILTKCH16CQ2502SI8ZNMTM67VS',
//   package: 'prepay_id=wx201410272009395522657a690389285100'
// };

// const apiKey = 'your_api_key_here';
// const base64Signature = generateBase64Signature(data, apiKey);
// console.log('Base64 Signature:', base64Signature);
// Base64 Signature: uOVRnA4qG/MNnYzdQxJanN+zU+lTgIcnU9BxGw5dKjK+VdEUz2FeIoC+D5sB/LN+nGzX3hfZg6r5wT1pl2ZobmIc6p0ldN7J6yDgUzbX8Uk3sD4a4eZVPTBvqNDoUqcYMlZ9uuDdCvNv4TM3c1WzsXUrExwVkI1XO5jCNbgDJ25nkT/c1gIFvqoogl7MdSFGc4W4xZsqCItnqbypR3RuGIlR9h9vlRsy7zJR9PBI83X8alLDIfR1ukt1P7tMnmogZ0cuDY8cZsd8ZlCgLadmvej58SLsIkVxFJ8XyUgx9FmutKSYTmYtWBZ0+tNvfGmbXU7cob8H/4nLBiCwIUFluw==


module.exports = {
  generatePaymentXML,
  generateRandomString,
  generateBase64Signature,
}